package com.web.homework01;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.*;

@WebFilter(urlPatterns = "/autologin.html")
public class DownloadAuto implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //设置返回值编码格式
        servletResponse.setContentType("text/html;charset=utf-8");
        //强转请求格式
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //获取Cookie存储的账号密码信息
        Cookie[] cookies = req.getCookies();
        Cookie userCookie = getCookie(cookies, "userName");
        Cookie passCookie = getCookie(cookies, "password");
        //判断Cookie存储值是否为空
        if (userCookie != null && passCookie != null) {
            //若不为空拿出Cookie中账号和密码与数据库中数据进行比较，
            //  若相同则放行并登录，不同则让用户录入账号和密码
            //为空则放行让用户输入账号密码
            String user = userCookie.getValue();
            String pass = passCookie.getValue();
            String password = null;
            String username = null;
            try {
                String url = "jdbc:mysql://127.0.0.1:3306/demo";
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection conn = DriverManager.getConnection(url, "root", "root");
                PreparedStatement stmt = conn.prepareStatement("select password,username from users where username = ?");
                stmt.setString(1, user);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    password = rs.getString("password");
                    username = rs.getString("username");

                }
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }


            if (username.equals(user) && password.equals(pass)) {
                servletResponse.getWriter().write("登录成功");
                return;
            } else {
                filterChain.doFilter(req, servletResponse);
                return;
            }
        } else {
            filterChain.doFilter(req, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }


    private Cookie getCookie(Cookie[] cookies, String cookieName) {
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie;
            }
        }
        return null;
    }
}
